package cn.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//文件下载类
public final class FileDownload {
	private FileDownload() {
	}

	/**
	 * 文件的下载
	 * 
	 * @param request请求
	 * @param response响应
	 * @param fileName下载文件名称
	 * @param originFile下载文件在服务器中的路径
	 */
	public static void download(//
			HttpServletRequest request, //
			HttpServletResponse response, //
			String fileName, String originFile) {
		// 1、构造流对象
		InputStream is = null;
		OutputStream out = null;
		// 2、设置响应头
		try {
			response.setHeader("content-disposition", "attchment;filename="
					+ URLEncoder.encode(fileName, "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 3、设置响应数据类型
		response.setContentType("multipart/form-data");
		// 4、边读边写
		byte[] bt = new byte[1024];
		int len;
		try {
			is = new FileInputStream(originFile);
			// 一定写向response
			out = response.getOutputStream();
			while ((len = is.read(bt)) != -1) {
				out.write(bt, 0, len);
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 5、关闭资源
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		// 6、删除已经下载后的文件
		new File(originFile).delete();
	}
}
